package com.health.fragment.jtys;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.health.adapter.JTYSDAAdapter;
import com.health.adapter.SearchDaAdapter;
import com.health.model.JBBean;
import com.health.model.PeopleType;
import com.health.tools.AutoLoadListener;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.ViewUtils;
import com.health.viewscontrols.MainActivity_Menu_Tj;
import com.health.viewscontrols.MoreSearch;
import com.health.viewscontrols.NovaApplication;
import com.health.R;
import com.health.db.DbManager;
import com.health.db.FDbManager;
import com.health.fragment.NovaFragment;
import com.health.model.PageData;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tools.DeleteDAData;
import com.health.tools.SPUtil;
import com.health.viewscontrols.focusgroup.ScreenSearchActivity;
import com.health.viewscontrols.qyinfo.MemberDataActivity;
import com.health.widget.CommomDialog;
import com.health.widget.MyScrollView;
import com.nova.BaseFragmentActivity;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

/**
 * 家庭医生档案
 *
 * @author nova
 */
public class JTYSDA extends NovaFragment
        implements OnClickListener, android.widget.CompoundButton.OnCheckedChangeListener {

    private View docDAView = null;
    private GridView gd_da;

    // public static List<ARCHIVE_BASEINFO> infos_signed;
    // private RadioGroup rg;
    // private RadioButton rb_all;
    // private RadioButton rb_checked;
    // private RadioButton rb_unchecked;
    private EditText et_content_search;
    private ImageButton ib_search;
    private LinearLayout ib_select;

    private Button btn_top;
    private Button btn_next;

    private TextView tv_allpage;
    private TextView tv_cupage;

    public final static String TYPE_ALL = "all";
    public final static String TYPE_SIGN = "sign";
    public final static String TYPE_UNSIGN = "unsign";
    private static String typeSignContent = "";// 类型

    private String searchContent = "";//搜索内容
    private int pagesize = 9;
    private int pageall = 1;
    private PageData nd;
    private JTYSDAAdapter jtysDAAdapter = null;
    private ARCHIVE_BASEINFO userinfo = null;
    private FDbManager fdbmanger = null;
    private String str_jdr = "";
    private String str_jdrno = "";
    private List<ARCHIVE_BASEINFO> infos = new ArrayList<>();
    private ImageView ib_delete;

    private String strIntentId = "";
    private RecyclerView rv_listsearch;
    private LinearLayout ll_search;
    private LinearLayout ll_head2;
    private int topHeight;
    private List<ARCHIVE_BASEINFO> newInfo;
    private String isFirstLoad = "0";
    private String currentSelectId = "";
    private String searchContent2;
    private String moreSearchJb = "";
    private SearchDaAdapter daAdapter;
    private List<JBBean> jbData;


    @Override
    public View findViews(LayoutInflater inflater) {
        userinfo = NovaApplication.getUserInfo();
        fdbmanger = NovaApplication.fdbmanger;
        docDAView = inflater.inflate(R.layout.jtys_da, null);

        str_jdr = SPUtil.getstr_jdr(getActivity());
        str_jdrno = SPUtil.getStr_jdrno(getActivity());
        pagesize = NovaApplication.dbManger.pagesize;
        // infos_signed =
        // NovaApplication.dbManger.selectUserByQYSign(str_jdrno);
        initViews(docDAView);
        AutoLoadListener autoLoadListener = new AutoLoadListener(callBack);
        gd_da.setOnScrollListener(autoLoadListener);
        typeSignContent = TYPE_ALL;
        return docDAView;
    }



    @Override
    public void onStart() {
        super.onStart();
        if (isAdded()) {//判断Fragment已经依附Activity
            strIntentId = getArguments().getString(GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID);
            Log.e("JTYSDA", strIntentId);
        }
    }

    @Override
    public void setupView(View view) {

    }

    @Override
    public void addListener() {
        ib_search.setOnClickListener(this);
        ib_delete.setOnClickListener(this);
        ib_select.setOnClickListener(this);
        btn_top.setOnClickListener(this);
        btn_next.setOnClickListener(this);
        ll_search.setOnClickListener(this);
        et_content_search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchContent = s + "";
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    public void setData() {
        jbData = new ArrayList<>();

        JBBean bean = new JBBean();
        bean.setJbName("一般人群");
        bean.setJbId("1");
        Log.e("TAG","一般人群数目："+NovaApplication.dbManger.getCountByJDRType(str_jdrno, PeopleType.YBRQ));
        bean.setJbNum(NovaApplication.dbManger.getCountByJDRType(str_jdrno, PeopleType.YBRQ)+"");
        jbData.add(bean);
        JBBean bean2 = new JBBean();
        bean2.setJbName("儿童");
        bean2.setJbId("2");
        bean2.setJbNum(NovaApplication.dbManger.getCountByJDRType(str_jdrno, PeopleType.CHILD)+"");
        jbData.add(bean2);
        JBBean bean3 = new JBBean();
        bean3.setJbName("高血压");
        bean3.setJbId("6");
        bean3.setJbNum(NovaApplication.dbManger.getCountByJDRType(str_jdrno, PeopleType.GXY)+"");
        jbData.add(bean3);
        JBBean bean4 = new JBBean();
        bean4.setJbName("糖尿病");
        bean4.setJbId("7");
        bean4.setJbNum(NovaApplication.dbManger.getCountByJDRType(str_jdrno, PeopleType.TNB)+"");
        jbData.add(bean4);
        JBBean bean5 = new JBBean();
        bean5.setJbName("精神病");
        bean5.setJbId("5");
        bean5.setJbNum(NovaApplication.dbManger.getCountByJDRType(str_jdrno, PeopleType.JSB)+"");
        jbData.add(bean5);
        JBBean bean6 = new JBBean();
        bean6.setJbName("脑卒中");
        bean6.setJbId("9");
        bean6.setJbNum(NovaApplication.dbManger.getCountByJDRType(str_jdrno, PeopleType.NCZ)+"");
        jbData.add(bean6);
        JBBean bean7 = new JBBean();
        bean7.setJbName("冠心病");
        bean7.setJbId("8");
        bean7.setJbNum(NovaApplication.dbManger.getCountByJDRType(str_jdrno, PeopleType.GXB)+"");
        jbData.add(bean7);
        NovaApplication.dbManger.getCountByJDRTypeTest();
        for(JBBean jbData2: jbData){
            System.out.println("数据："+jbData2.getJbName());
        }

        daAdapter = new SearchDaAdapter(getActivity(), jbData, jbData.size(), new SearchDaAdapter.OnClickListener() {
            @Override
            public void setOnClickItemListener(View view, int position, String name, String id) {
                Log.e("TAG","选中条码："+name+"--"+id);
                currentSelectId = id;
                infos = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectAllJBPerson(str_jdrno, 1, DbManager.TYPE_ALL, id);
//                for(ARCHIVE_BASEINFO info:infos){
//                    System.out.println("搜索结果："+info.getCUSTOMERNAME());
//                }

                if (infos.size() > 0) {
                    jtysDAAdapter = new JTYSDAAdapter(getActivity(), infos, "all", gd_da,strIntentId);
                    gd_da.setAdapter(jtysDAAdapter);
                    jtysDAAdapter.notifyDataSetChanged();
                }else{
                    infos.removeAll(infos);
                    jtysDAAdapter = new JTYSDAAdapter(getActivity(), infos, "all", gd_da,strIntentId);
                    gd_da.setAdapter(jtysDAAdapter);
                    jtysDAAdapter.notifyDataSetChanged();
                }
            }
        });
        rv_listsearch.setAdapter(daAdapter);
        GridLayoutManager manager = new GridLayoutManager(getContext(), 7);

        //设置布局管理者
        rv_listsearch.setLayoutManager(manager);

        gd_da.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("档案已点击");
                if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {
                    userinfo = infos.get(position);
                    NovaApplication.setUserInfo(userinfo);
                    SPUtil.setstr_idCard(getContext(), userinfo.getIDCARD());
                    if (userinfo != null) {
                        Log.e("档案点击事件！！！", userinfo.getCUSTOMERNAME() + "\n" + userinfo.getIDCARD());
                        Intent intent = new Intent(getActivity(), MainActivity_Menu_Tj.class);
                        getActivity().startActivity(intent);
                    }
                } else if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MEMBER.equals(strIntentId)) {
                    Intent intent = new Intent();
                    userinfo = infos.get(position);
                    intent.putExtra("relation",userinfo);

                    ((MemberDataActivity)getActivity()).setResult(RESULT_OK, intent);
                    ((MemberDataActivity)getActivity()).finish();

                }
            }
        });
    }

    private void setDatasByType(String typeSign) {

        if (infos == null) {
            infos = new ArrayList<>();
        }
        nd = new PageData();
        // nd.setCurrentPage("1");
        nd.setCountall(pageall);
        nd.setCountcurrent(1);

        typeSignContent = typeSign;
        int count = 0;
        if (TYPE_ALL.equals(typeSign)) {
            count = NovaApplication.dbManger.getCountByJDR(str_jdrno, str_jdrno, searchContent);
        } else if (TYPE_SIGN.equals(typeSign)) {
            count = NovaApplication.dbManger.getCountByJDRSign(getActivity(),str_jdrno);
        } else if (TYPE_UNSIGN.equals(typeSign)) {
            count = NovaApplication.dbManger.getCountByJDRUnSign(str_jdrno, str_jdrno, searchContent);
        }

        Log.w("eeeeeeeeeeepagcount", "" + count);

        if (count > 0) {

            pageall = count % pagesize == 0 ? count / pagesize : count / pagesize + 1;
            nd.setCountall(pageall);
            nd.setCountcurrent(1);
            getPageData2(typeSign, 1);
        } else {
            nd = new PageData();
            // nd.setCurrentPage("1");
            nd.setCountall(pageall);
            nd.setCountcurrent(1);
            tv_allpage.setText("");
            tv_cupage.setText("");
            gd_da.setAdapter(null);
        }
        setButtonBg();

        gd_da.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {

                    // IS_UPDATE //Y 未上传 N已上传
//                    if ("Y".equals(infos.get(position).getIS_UPDATE())) {
                        showDeleteDialog(position);
//                    }
                }
                return true;
            }
        });
    }


    private void setDatasByType2(String typeSign,String jb,String sex) {

        if (infos == null) {
            infos = new ArrayList<>();
        }
        nd = new PageData();
        // nd.setCurrentPage("1");
        nd.setCountall(pageall);
        nd.setCountcurrent(1);

        typeSignContent = typeSign;
        int count = 0;
        if (TYPE_ALL.equals(typeSign)) {
            count = NovaApplication.dbManger.getCountByJDR(str_jdrno, str_jdrno, searchContent);
        } else if (TYPE_SIGN.equals(typeSign)) {
            count = NovaApplication.dbManger.getCountByJDRSign(getActivity(),str_jdrno);
        } else if (TYPE_UNSIGN.equals(typeSign)) {
            count = NovaApplication.dbManger.getCountByJDRUnSign(str_jdrno, str_jdrno, searchContent);
        }

        Log.w("eeeeeeeeeeepagcount", "" + count);

        if (count > 0) {

            pageall = count % pagesize == 0 ? count / pagesize : count / pagesize + 1;
            nd.setCountall(pageall);
            nd.setCountcurrent(1);
            getPageData2(typeSign, 1);
        } else {
            nd = new PageData();
            // nd.setCurrentPage("1");
            nd.setCountall(pageall);
            nd.setCountcurrent(1);
            tv_allpage.setText("");
            tv_cupage.setText("");
            gd_da.setAdapter(null);
        }
        setButtonBg();

        gd_da.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {

                    // IS_UPDATE //Y 未上传 N已上传
//                    if ("Y".equals(infos.get(position).getIS_UPDATE())) {
                        showDeleteDialog(position);
//                    }
                }
                return true;
            }
        });
    }
    /**
     * 获取分页数据
     *
     * @param type
     * @author 王婷婷
     * @date 2018年1月16日 下午7:08:17
     */
    private void getPageData(String type, int currentPage) {
        List<ARCHIVE_BASEINFO> newInfo = new ArrayList<>();
        tv_allpage.setText("总页数：" + pageall);
        tv_cupage.setText("当前页：" + currentPage);
        Log.w("eeeeeeeeeeepageall", "" + pageall);
        if (TYPE_ALL.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>)NovaApplication.dbManger.selectUserByQYSignPage(str_jdrno, currentPage,
                    DbManager.TYPE_ALL, searchContent);
        } else if (TYPE_SIGN.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(str_jdrno, currentPage,
                    DbManager.TYPE_SIGN, searchContent);
        } else if (TYPE_UNSIGN.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(str_jdrno, currentPage,
                    DbManager.TYPE_UNSIGN, searchContent);
        }

        if(currentSelectId != null && !currentSelectId.equals("")) {
            newInfo = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectAllJBPerson(str_jdrno, currentPage, DbManager.TYPE_ALL, currentSelectId);
        }

        if (newInfo.size() > 0) {
            for (ARCHIVE_BASEINFO mInfo:newInfo){

                infos.add(mInfo);
            }


            jtysDAAdapter = new JTYSDAAdapter(getActivity(), infos, type, gd_da,strIntentId);
            gd_da.setAdapter(jtysDAAdapter);
            jtysDAAdapter.notifyDataSetChanged();
            if(isFirstLoad == "1") {
                gd_da.smoothScrollToPosition(jtysDAAdapter.getCount() - 12);
            }
        }

        gd_da.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("档案已点击");
                if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {
                    userinfo = infos.get(position);
                    NovaApplication.setUserInfo(userinfo);
                    SPUtil.setstr_idCard(getContext(), userinfo.getIDCARD());
                    if (userinfo != null) {
                        Log.e("档案点击事件！！！", userinfo.getCUSTOMERNAME() + "\n" + userinfo.getIDCARD());
                        Intent intent = new Intent(getActivity(), MainActivity_Menu_Tj.class);
                        getActivity().startActivity(intent);
                    }
                } else if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MEMBER.equals(strIntentId)) {
                    Intent intent = new Intent();
                    userinfo = infos.get(position);
                    intent.putExtra("relation",userinfo);

                    ((MemberDataActivity)getActivity()).setResult(RESULT_OK, intent);
                    ((MemberDataActivity)getActivity()).finish();

                }
            }
        });
    }


    private void getPageData2(String type, int currentPage) {
        List<ARCHIVE_BASEINFO> newInfo = new ArrayList<>();
        tv_allpage.setText("总页数：" + pageall);
        tv_cupage.setText("当前页：" + currentPage);
        Log.w("getPageData2()", "" + pageall);
        Log.e("TAG","搜索内容："+searchContent);
        if (TYPE_ALL.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>)NovaApplication.dbManger.selectUserByQYSignPage2(str_jdrno, currentPage,
                    DbManager.TYPE_ALL, searchContent);
        } else if (TYPE_SIGN.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(str_jdrno, currentPage,
                    DbManager.TYPE_SIGN, searchContent);
        } else if (TYPE_UNSIGN.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(str_jdrno, currentPage,
                    DbManager.TYPE_UNSIGN, searchContent);
        }

        infos = new ArrayList<>();
        if (newInfo.size() > 0) {
            for (ARCHIVE_BASEINFO mInfo:newInfo){

                infos.add(mInfo);
            }


            jtysDAAdapter = new JTYSDAAdapter(getActivity(), infos, type, gd_da,strIntentId);
            gd_da.setAdapter(jtysDAAdapter);
            jtysDAAdapter.notifyDataSetChanged();
            if(isFirstLoad == "1") {
                gd_da.smoothScrollToPosition(jtysDAAdapter.getCount() - 12);
            }
        }

        gd_da.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("档案已点击");
                if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {
                    userinfo = infos.get(position);
                    NovaApplication.setUserInfo(userinfo);
                    SPUtil.setstr_idCard(getContext(), userinfo.getIDCARD());
                    if (userinfo != null) {
                        Log.e("档案点击事件！！！", userinfo.getCUSTOMERNAME() + "\n" + userinfo.getIDCARD());
                        Intent intent = new Intent(getActivity(), MainActivity_Menu_Tj.class);
                        getActivity().startActivity(intent);
                    }
                } else if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MEMBER.equals(strIntentId)) {
                    Intent intent = new Intent();
                    userinfo = infos.get(position);
                    intent.putExtra("relation",userinfo);

                    ((MemberDataActivity)getActivity()).setResult(RESULT_OK, intent);
                    ((MemberDataActivity)getActivity()).finish();

                }
            }
        });
    }


    private void getPageData3(String type, int currentPage) {
        List<ARCHIVE_BASEINFO> newInfo = new ArrayList<>();
        tv_allpage.setText("总页数：" + pageall);
        tv_cupage.setText("当前页：" + currentPage);
        Log.w("eeeeeeeeeeepageall", "" + pageall);
        if (TYPE_ALL.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>)NovaApplication.dbManger.selectUserByQYSignPage(str_jdrno, currentPage,
                    DbManager.TYPE_ALL, searchContent);
        } else if (TYPE_SIGN.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(str_jdrno, currentPage,
                    DbManager.TYPE_SIGN, searchContent);
        } else if (TYPE_UNSIGN.equals(type)) {
            newInfo = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectUserByQYSignPage(str_jdrno, currentPage,
                    DbManager.TYPE_UNSIGN, searchContent);
        }

        if(currentSelectId != null && !currentSelectId.equals("")) {
            newInfo = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectAllJBPerson(str_jdrno, currentPage, DbManager.TYPE_ALL, currentSelectId);
        }

        if (newInfo.size() > 0) {
            for (ARCHIVE_BASEINFO mInfo:newInfo){

                infos.add(mInfo);
            }


            jtysDAAdapter = new JTYSDAAdapter(getActivity(), infos, type, gd_da,strIntentId);
            gd_da.setAdapter(jtysDAAdapter);
            jtysDAAdapter.notifyDataSetChanged();
        }

        gd_da.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("档案已点击");
                if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {
                    userinfo = infos.get(position);
                    NovaApplication.setUserInfo(userinfo);
                    SPUtil.setstr_idCard(getContext(), userinfo.getIDCARD());
                    if (userinfo != null) {
                        Log.e("档案点击事件！！！", userinfo.getCUSTOMERNAME() + "\n" + userinfo.getIDCARD());
                        Intent intent = new Intent(getActivity(), MainActivity_Menu_Tj.class);
                        getActivity().startActivity(intent);
                    }
                } else if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MEMBER.equals(strIntentId)) {
                    Intent intent = new Intent();
                    userinfo = infos.get(position);
                    intent.putExtra("relation",userinfo);

                    ((MemberDataActivity)getActivity()).setResult(RESULT_OK, intent);
                    ((MemberDataActivity)getActivity()).finish();

                }
            }
        });
    }

    AutoLoadListener.AutoLoadCallBack callBack = new AutoLoadListener.AutoLoadCallBack() {

        public void execute() {
            isFirstLoad = "1";
        }

    };

    /**
     * 初始化布局
     *
     * @author 王婷婷
     * @date 2017年2月10日 下午3:17:44
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initViews(View v) {

        gd_da = v.findViewById(R.id.gd_da);
        ll_head2 = (LinearLayout)v.findViewById(R.id.ll_head2);
        et_content_search = (EditText) v.findViewById(R.id.et_content_search);
        ib_search = (ImageButton) v.findViewById(R.id.ib_search);
        ib_delete = (ImageView) v.findViewById(R.id.ib_delete);
        ib_select = v.findViewById(R.id.ib_select);

        btn_top = (Button) v.findViewById(R.id.btn_top);
        btn_next = (Button) v.findViewById(R.id.btn_next);
        rv_listsearch = (RecyclerView)v.findViewById(R.id.rv_listsearch);
        tv_allpage = (TextView) v.findViewById(R.id.tv_allpage);
        LinearLayout ll_back = (LinearLayout)v.findViewById(R.id.ll_back);
        ll_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        tv_cupage = (TextView) v.findViewById(R.id.tv_cupage);
        ll_search = (LinearLayout)v.findViewById(R.id.ll_search);
        if(NovaApplication.isBoolean_zhuyuan()){
            et_content_search.setHint("身份证或后四位/手机号/姓名/住院号");
        }else{
            et_content_search.setHint("身份证或后四位/手机号/姓名");
        }
        TextView tvJg = (TextView)v.findViewById(R.id.tv_jg);
        SharedPreferences shareDatas = getActivity().getSharedPreferences(SPUtil.SP_NAME, Context.MODE_PRIVATE);
        String jg = shareDatas.getString(SPUtil.STR_JDDW,"");
        tvJg.setText(jg);

        gd_da.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        if (view.getLastVisiblePosition() == (view.getCount()-1)) {
//                            nextData();
                        }
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        // 判断滚动到底部
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        });

        gd_da.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("档案已点击");
                if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {
                    userinfo = infos.get(position);
                    NovaApplication.setUserInfo(userinfo);
                    SPUtil.setstr_idCard(getContext(), userinfo.getIDCARD());
                    if (userinfo != null) {
                        Log.e("档案点击事件！！！", userinfo.getCUSTOMERNAME() + "\n" + userinfo.getIDCARD());
                        Intent intent = new Intent(getActivity(), MainActivity_Menu_Tj.class);
                        getActivity().startActivity(intent);
                    }
                } else if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MEMBER.equals(strIntentId)) {
                    Intent intent = new Intent();
                    userinfo = infos.get(position);
                    intent.putExtra("relation",userinfo);

                    ((MemberDataActivity)getActivity()).setResult(RESULT_OK, intent);
                    ((MemberDataActivity)getActivity()).finish();

                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            if(moreSearchJb.equals("")){
                if(currentSelectId.equals("")){
                    infos = new ArrayList<>();
                    setDatasByType(typeSignContent);
                    Log.e("TAG","onResume()");
                    setButtonBg();
                }else if(infos.size() == 0){
                    infos = new ArrayList<>();
                    setDatasByType(typeSignContent);
                    Log.e("TAG","onResume()");
                    setButtonBg();
                }
            }else if(infos.size() == 0){
                infos = new ArrayList<>();
                setDatasByType(typeSignContent);
                Log.e("TAG","onResume()");
                setButtonBg();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_search: // 搜索
                Log.e("tag", searchContent + "-------------content_search");
                setDatasByType(typeSignContent);
                break;

            case R.id.ib_delete: // 搜索
                et_content_search.setText("");
                et_content_search.setHint("身份证或后四位/手机号/姓名/住院号");
                break;

            case R.id.ib_select: // 筛选按钮
//                showPopupWindow();
                Intent intent = new Intent(getActivity(), ScreenSearchActivity.class);
                startActivityForResult(intent,1);
                break;

            case R.id.ll_search:
                Intent intent2 = new Intent(getActivity(), MoreSearch.class);
                startActivityForResult(intent2,1);
                break;

            case R.id.bt_search: // 筛选
                if (detail_state_yqy.isChecked()) {
                    // 已签约
                    setDatasByType(TYPE_SIGN);
                    Log.e("tag", "已签约");
                } else if (detail_state_wqy.isChecked()) {
                    // 未签约
                    setDatasByType(TYPE_UNSIGN);
                    Log.e("tag", "未签约");
                } else {
                    setDatasByType(TYPE_ALL);
                }
                // gd_da.setAdapter(jtysDAAdapter);
                // jtysDAAdapter.notifyDataSetChanged();
                popWindow.dismiss();
                break;
            case R.id.bt_clear: // 清空
                for (int i = 0; i < peopleGroupChecks.size(); i++) {
                    peopleGroupChecks.get(i).setChecked(false);
                }
                // detail_state_yqy.setChecked(false);
                // detail_state_wqy.setChecked(false);
                rg_state_qy.clearCheck();

                detail_state_ysf.setChecked(false);
                detail_state_xsf.setChecked(false);
                break;
            case R.id.btn_top:
                preData();
                break;
            case R.id.btn_next:
                nextData();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 200)//之前提到的两个标志，在这里显示出了作用
        {
            String data1 = data.getStringExtra("data");
            Log.e("TAG","搜索信息："+data1);
            searchContent = data1;
            setDatasByType(typeSignContent);
            daAdapter.refresh(jbData);
        }else if(requestCode == 1 && resultCode == 600){
            infos = new ArrayList<>();
            String sex = data.getStringExtra("sex");
            String jb = data.getStringExtra("jb");
            moreSearchJb = jb+sex;
            Log.e("TAG","搜索信息："+jb+"--"+sex);
            daAdapter.refresh(jbData);
//            setDatasByType2(typeSignContent,jb,sex);
            try {
                infos = (List<ARCHIVE_BASEINFO>) NovaApplication.dbManger.selectAllJBPersonSex(str_jdrno, 1, DbManager.TYPE_ALL, jb, sex);
                Log.e("TAG", "搜索大小：" + infos.size());
                if (infos.size() > 0) {
                    jtysDAAdapter = new JTYSDAAdapter(getActivity(), infos, "all", gd_da, strIntentId);
                    gd_da.setAdapter(jtysDAAdapter);
                    jtysDAAdapter.notifyDataSetChanged();
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            moreSearchJb = "";
                        }
                    },1500);
                } else {
                    infos.removeAll(infos);
                    jtysDAAdapter = new JTYSDAAdapter(getActivity(), infos, "all", gd_da, strIntentId);
                    gd_da.setAdapter(jtysDAAdapter);
                    jtysDAAdapter.notifyDataSetChanged();
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            moreSearchJb = "";
                        }
                    },1500);
                }
            }catch (Exception e){
                Log.e("TAG", "异常：" + e.toString());
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void preData() {
        // 上一页
        if (nd.getCountcurrent() > nd.getCountall()) {
            nd.setCountcurrent(nd.getCountall());
        }

        if (nd.getCountcurrent() == 1) {
//            ((BaseFragmentActivity) getActivity()).showTextDialog("已经是第一页了");
            btn_top.setBackground(getResources().getDrawable(R.drawable.btn_top2));
        } else {
            nd.setCountcurrent(nd.getCountcurrent() - 1);
            infos = new ArrayList<>();
            gd_da.setAdapter(null);
            getPageData(typeSignContent, nd.getCountcurrent());
        }
        setButtonBg();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void nextData() {

        if (nd.getCountcurrent() > nd.getCountall()) {
            nd.setCountcurrent(nd.getCountall());
        }

        if (nd.getCountcurrent() == nd.getCountall()) {
//            ((BaseFragmentActivity) getActivity()).showTextDialog("已经是最后一页了");
            btn_next.setBackground(getResources().getDrawable(R.drawable.btn_bottom2));
        } else {
            nd.setCountcurrent(nd.getCountcurrent() + 1);
//            infos = new ArrayList<>();
            gd_da.setAdapter(null);
            getPageData(typeSignContent, nd.getCountcurrent());
        }

        setButtonBg();
    }

    /**
     * 设置背景色
     *
     * @author 王婷婷
     * @date 2016年2月22日 上午11:21:24
     */
    @SuppressLint("NewApi")
    private void setButtonBg() {
        if (nd.getCountcurrent() == 1) {
            if(nd.getCountall()<=1){
                btn_top.setBackground(getResources().getDrawable(R.drawable.btn_top2));
                btn_next.setBackground(getResources().getDrawable(R.drawable.btn_bottom2));
            }else{
                btn_top.setBackground(getResources().getDrawable(R.drawable.btn_top2));
                btn_next.setBackground(getResources().getDrawable(R.drawable.btn_bottom1));
            }

        } else if (nd.getCountcurrent() == nd.getCountall()) {
            btn_top.setBackground(getResources().getDrawable(R.drawable.btn_top1));
            btn_next.setBackground(getResources().getDrawable(R.drawable.btn_bottom2));
            Toast.makeText(getContext(), "最后一页", Toast.LENGTH_SHORT).show();
        } else if ((nd.getCountcurrent() > 1) && (nd.getCountcurrent() < nd.getCountall())) {
            btn_top.setBackground(getResources().getDrawable(R.drawable.btn_top1));
            btn_next.setBackground(getResources().getDrawable(R.drawable.btn_bottom1));
        }
    }

    private PopupWindow popWindow;
    private Button bt_clear;
    private Button bt_search;

    private CheckBox people1;
    private CheckBox people2;
    private CheckBox people3;
    private CheckBox people4;
    private CheckBox people5;
    private CheckBox people6;
    private CheckBox people7;
    private CheckBox people8;
    private CheckBox people9;
    private CheckBox people10;
    private int age;
    private List<CheckBox> peopleGroupChecks = new ArrayList<CheckBox>();

    private RadioButton detail_state_yqy;
    private RadioButton detail_state_wqy;
    private RadioGroup rg_state_qy;

    private CheckBox detail_state_xsf;
    private CheckBox detail_state_ysf;

    private void showPopupWindow() {

        if (popWindow == null) {
            View contentView = LayoutInflater.from(getContext()).inflate(R.layout.popuplayout, null);
            initPopView(contentView);

            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);

            int width = wm.getDefaultDisplay().getWidth() / 4;
            int height = wm.getDefaultDisplay().getHeight() / 4;
            // 创建一个PopuWidow对象
            popWindow = new PopupWindow(contentView, width, height);
            Button bt_clear = (Button) contentView.findViewById(R.id.bt_clear);
            Button bt_search = (Button) contentView.findViewById(R.id.bt_search);
            // 人群分类
            people1 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup1_ch);
            people2 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup2_ch);
            people3 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup3_ch);
            people4 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup4_ch);
            people5 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup5_ch);
            people6 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup6_ch);
            people7 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup7_ch);
            people8 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup8_ch);
            people9 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup9_ch);
            people10 = (CheckBox) contentView.findViewById(R.id.detail_peoplegroup10_ch);

            peopleGroupChecks.add(people1);
            peopleGroupChecks.add(people2);
            peopleGroupChecks.add(people3);
            peopleGroupChecks.add(people4);
            peopleGroupChecks.add(people5);
            peopleGroupChecks.add(people6);
            peopleGroupChecks.add(people7);
            peopleGroupChecks.add(people8);
            peopleGroupChecks.add(people9);
            peopleGroupChecks.add(people10);
            for (CheckBox cb : peopleGroupChecks) {
                cb.setOnCheckedChangeListener(this);
            }

            // 签约状态
            detail_state_yqy = (RadioButton) contentView.findViewById(R.id.detail_state_yqy);
            detail_state_wqy = (RadioButton) contentView.findViewById(R.id.detail_state_wqy);
            rg_state_qy = (RadioGroup) contentView.findViewById(R.id.rg_state_qy);
            detail_state_yqy.setOnCheckedChangeListener(this);
            detail_state_wqy.setOnCheckedChangeListener(this);

            // 随访
            detail_state_xsf = (CheckBox) contentView.findViewById(R.id.detail_state_xsf);
            detail_state_ysf = (CheckBox) contentView.findViewById(R.id.detail_state_ysf);
            detail_state_xsf.setOnCheckedChangeListener(this);
            detail_state_ysf.setOnCheckedChangeListener(this);

            bt_clear.setOnClickListener(this);
            bt_search.setOnClickListener(this);
        }
        // 使其聚集 ，要想监听菜单里控件的事件就必须要调用此方法
        popWindow.setFocusable(true);
        // 设置允许在外点击消失
        popWindow.setOutsideTouchable(true);
        // 设置背景，这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));

        popWindow.showAsDropDown(ib_select, 0, 0);
        popWindow.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

        // 监听触屏事件
        popWindow.setTouchInterceptor(new OnTouchListener() {
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    popWindow.dismiss();
                    return true;
                }
                return false;
            }
        });

    }

    private void initPopView(View contentView) {

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (people1.isChecked()) {
            for (int i = 1; i < peopleGroupChecks.size(); i++) {
                peopleGroupChecks.get(i).setChecked(false);
            }
        }

        if (detail_state_ysf.isChecked()) {
            detail_state_xsf.setChecked(false);
        }
        if (detail_state_xsf.isChecked()) {
            detail_state_ysf.setChecked(false);
        }

    }

    /**
     * 显示删除档案对话框
     *
     * @param position
     * @author 王婷婷
     * @date 2017年12月18日 下午5:31:27
     */
    private void showDeleteDialog(final int position) {
        new CommomDialog(getActivity(), R.style.dialog, "", new CommomDialog.OnCloseListener() {

            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    DeleteDAData.deleteDaData(infos.get(position).getIDCARD());
                    setDatasByType(JTYSDA.typeSignContent);
                    dialog.dismiss();
                }

            }

        }).setTitle("是否删除档案").setPositiveButton("删除").setNegativeButton("取消").show();
    }

}
